﻿using System.Web.Mvc;
using System;

namespace smartcrm.Utilities
{
    /// <summary>
    /// Indicate that user must login
    /// Use AllowAnonymousAttribute to specify an exception    
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class PortalAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
    {
        public static String AuthUrl = System.Configuration.ConfigurationManager.AppSettings["PortalAuthUrl"];
        public static String AuthSaveKey = System.Configuration.ConfigurationManager.AppSettings["PortalAuthSaveKey"];
        public static String AuthSaveType = System.Configuration.ConfigurationManager.AppSettings["AuthSaveType"];
        
        /// <summary>
        /// Handle login
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext == null)
            {
                throw new Exception("This attribute only apply on web application");
            }
            else
            {
                switch (AuthSaveType.ToUpper())
                {
                    case "SESSION":
                        if (filterContext.HttpContext.Session == null)
                        {
                            throw new Exception("Server Session unavailable");
                        }
                        else if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)&&
                            !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                        {
                            if (filterContext.HttpContext.Session[AuthSaveKey] == null)
                            {
                                filterContext.Result = new RedirectResult(AuthUrl);
                            }
                        }
                        break;
                    case "COOKIE":
                        if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)&& 
                            !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                        {
                            if (filterContext.HttpContext.Request.Cookies[AuthSaveKey] == null)
                            {
                                filterContext.Result = new RedirectResult(AuthUrl);
                            }
                        }
                        break;
                    default:
                        throw new ArgumentNullException("Must be one of Cookie or Session");
                }
            }
        }
    }
}
